#include "doexcel.h"
#include "qt_windows.h"

DoExcel::DoExcel(QString name)
{
    ExcelName_ = name;
}

void DoExcel::GetAllData(QList<QList<QVariant>> &excel_list)
{
    //CoInitialize();
    HRESULT r = OleInitialize(0);
    if(r != S_OK && r != S_FALSE){
        OleUninitialize();
        return;
    }

    QAxObject *excel = new QAxObject(this);//建立excel操作对象
    excel->setControl("Excel.Application");//连接Excel控件
    excel->setProperty("Visible", false);//显示窗体看效果,选择ture将会看到excel表格被打开
    excel->setProperty("DisplayAlerts", true);//显示警告看效果
    QAxObject *workbooks = excel->querySubObject("WorkBooks");//获取工作簿(excel文件)集合

    workbooks->dynamicCall("Open(const QString&)", ExcelName_);//打开刚才选定的excel
    QAxObject *workbook = excel->querySubObject("ActiveWorkBook");
    QAxObject *worksheet = workbook->querySubObject("WorkSheets(int)",SheetIndex_);
    QAxObject *usedRange = worksheet->querySubObject("UsedRange");//获取表格中的数据范围

    QVariant var = usedRange->dynamicCall("Value");//将所有的数据读取刀QVariant容器中保存
    //QList<QList<QVariant>> excel_list;//用于将QVariant转换为Qlist的二维数组
    QVariantList varRows=var.toList();
    if(varRows.isEmpty())
     {
         return;
     }
    const int row_count = varRows.size();
    QVariantList rowData;
    for(int i=0;i<row_count;++i)
    {
        rowData = varRows[i].toList();
        excel_list.push_back(rowData);
    }//转换完毕


    //qDebug()<<excel_list.at(3).at(1).toInt();

    //然后将二维数组Qlist<Qlist<QVariant>>中的数据读取出来，到表格或者数据模型中，具体在这里过程省略

    workbook->dynamicCall( "Close(Boolean)", false );
    excel->dynamicCall( "Quit(void)" );
    delete excel;//因为前面选择了不显示excel窗口，如果这里不删除excel的话，excel依然是打开的，只是我们看不见（因为被隐藏

    OleUninitialize();
}

QString DoExcel::GetItemData(int row, int clom)
{
    return "";
}

QStringList DoExcel::GetItemDatas(int row, int clom, int w, int h)
{
    return QStringList("");
}

void DoExcel::SetName(const QString name)
{
    ExcelName_ = name;
}

QString DoExcel::GetName() const
{
    return ExcelName_;
}

void DoExcel::SetSheetIndex(const int index)
{
    SheetIndex_ = index;
}

QString DoExcel::GetSheetIndex() const
{
    return SheetIndex_;
}

void DoExcel::InstanceExcelObj()
{

}
